
<template>
  <div class="list">
    <!-- <li class="item" v-for="(item,key) in cities" :key="key" @click="handleLetterClick">{{key}}</li> -->
    <li
      class="item"
      v-for="item in letters"
      :key="item"
      :ref="item"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @click="handleLetterClick"
    >{{item}}</li>
  </div>
</template>
<script>
export default {
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: ""
    };
  },
  props: ["cities"],
  computed: {
    letters() {
      const letters = [];
      for (let i in this.cities) {
        letters.push(i);
      }
      return letters;
    }
  },
  updated() {
    //当父组件把cities数据传到这个数组时，钩子函数自动计算字母A 离屏幕上方的距离
    this.startY = this.$refs["A"][0].offsetTop;
  },
  methods: {
    handleLetterClick(e) {
      this.$emit("change", e.target.innerText);
    },
    handleTouchStart() {
      this.touchStatus = true;
    },
    handleTouchMove(e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 79;
          const index = Math.floor((touchY - this.startY) / 20);
          if (index >= 0 && index < this.letters.length) {
            this.$emit("change", this.letters[index]);
          }
        }, 16);
      }
    },
    handleTouchEnd() {
      this.touchStatus = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: absolute;
  top: 100px;
  right: 0;
  bottom: 0;
  width: 30px;
  .item {
    line-height: 30px;
    text-align: center;
    color: rgba(0, 38, 255, 0.527);
    list-style: none;
  }
}
</style>